package com.boot.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.boot.common.annotation.annotation.exception.NoLoginException;
import com.boot.util.CookieUtil;
import com.boot.vo.MessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

//import com.boot.entity.User;
//import com.boot.repository.UserRepository;

@Slf4j
@Component
public class NoLoginInterceptor extends HandlerInterceptorAdapter {
	public static final String TOKEN_KEY = "token";

	//@Autowired
	//	UserRepository userRepository;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		/**
		 *  获取cookie 解析用户id
		 *     如果用户id 存在 并且数据库中存在对应记录 请求合法   反之 用户未登录 请求非法
		 */
//		String username = NoLoginInterceptor.releaseUserNameFromCookie(request);
//		if (username == null || null == userRepository.findByUserName(username)) {
//			MessageHandler.createFailedVo("用户未登录");
//		}
		return super.preHandle(request, response, handler);
	}

	public static String releaseUserNameFromCookie(HttpServletRequest request){
		String userName = CookieUtil.getCookieValue(request, "userName");
		if (StringUtils.isBlank(userName)) {
			return null;
		}
		return userName;
	}


}





//	public static final String TOKEN_KEY = "token";
//	@Autowired
//	private UserRepository userRepository;
//	@Override
//	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//		boolean result = true;
//		System.out.println("=======");
//		try {
////			Integer id = TokenHandler.getBusinessId();
//			User u = null;
////			if(id==null||id==0)
////				result= false;
////			else {
////				u = userRepository.getOne(id);
////				if(u==null||u.getId()==null)
////					result = false;
////			}
////			if(!result)
////				response.sendRedirect("/login");
//		}catch (Exception e) {
//			e.printStackTrace();
//			result = false;
//			throw new Exception(e.getMessage());
//		}
//		return result;
//
//	}